/**
 * 报销单详情的底部按钮（员工查看）
 */
import React from 'react';
import menuRoute from 'routes/menuRoute'
import { connect } from 'react-redux'
import { messages, getToken } from "share/common";
import { Affix, Button, Modal, message } from "antd"

import Condition from 'components/condition'
const { If } = Condition;
import expenseReportFunction from 'containers/expense-report/expense-report.function'
const { getReportStatus } = expenseReportFunction;
import baseService from 'share/base.service'
import expenseReportService from 'containers/expense-report/expense-report.service'
import adminApproveListService from "containers/setting/process-monitoring-platform/admin-approve-list.service";
import 'styles/expense-report/components/buttons-bar-bottom.scss'

class ButtonsOnBottomBar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      deleting: false, //删除loading
      withdrawing: false, //撤回loading
      printLoading: false, //打印loading
      urgeLoading: false, // 催办 loading
      saving: false, //保存loading
    }
  }

  //删除
  handleDelete = () => {
    const { info } = this.props;
    Modal.confirm({
      title: messages('common.confirm.delete'/*确定要删除吗？*/),
      content: messages('common.after.delete'/*删除后无法恢复*/),
      okType: 'danger',
      onOk: () => {
        this.setState({ deleting: true });
        expenseReportService.deleteExpenseReport(info.expenseReportOID).then(res => {
          if (res.status === 200) {
            message.success(messages('expense-parent-report.key101')/*报销单已删除，关联费用会回到账本*/);
            this.goBack()
          }
        }).catch(e => {
          this.setState({ deleting: false });
          message.error(`${messages("common.operate.filed")/*操作失败*/}，${e.response.data.message}`)
        })
      }
    })
  };

  //撤回
  handleWithdraw = () => {
    const { info, approvalChains } = this.props;
    Modal.confirm({
      title: messages('expense-parent-report.key8'/*你确定要撤回吗？*/),
      onOk: () => {
        this.setState({ withdrawing: true });
        let params = {
          entities: [{
            entityOID: approvalChains[0] && approvalChains[0].entityOID,
            entityType: approvalChains[0] && approvalChains[0].entityType
          }]
        };
        expenseReportService.withdraw(params).then(res => {
          if (res.data.failNum > 0) {
            if (res.data.failReason[info.expenseReportOID]) {
              message.error(`${messages("common.operate.filed")/*操作失败*/}，${res.data.failReason[info.expenseReportOID]}`)
            } else {
              message.error(messages("common.operate.filed")/*操作失败*/)
            }
            this.setState({ withdrawing: false });
          } else {
            message.success(messages("common.operate.success")/*操作成功*/);
            this.goBack();
          }
        }).catch(e => {
          this.setState({ withdrawing: false });
          message.error(`${messages( "common.operate.filed")/*操作失败*/}，${e.response.data.message}`)
        })
      }
    });
  };

  //打印
  handlePrint = () => {
    const { info } = this.props;
    this.setState({ printLoading: true });
    baseService.printExpense(info.expenseReportOID).then(res => {
      this.setState({ printLoading: false });
      window.open(res.data.fileURL, "_blank")
    }).catch(e => {
      this.setState({ printLoading: false });
      message.error(e.response.data.message)
    })
  };

  //保存
  handleSave = () => {
    let { info, expenseReportInvoices } = this.props;
    info.expenseReportInvoices = expenseReportInvoices;
    if (info.applicantOID !== info.createdBy) {
      info.isProxy = 1
    }
    this.setState({ saving: true });
    expenseReportService.saveExpenseReport(info).then(() => {
      this.setState({ saving: false });
      message.success(messages('common.save.success', {name: ''}));
      this.goBack();
    }).catch(e => {
      this.setState({ saving: false });
      message.error(e.response.data.message);
    })
  };

  //返回
  goBack = () => {
    menuRoute.goBack(this)
    // this.context.router.push(menuRoute.getRouteItem('expense-report').url)
  };

  //催办
  handelUrge = () =>{
    const { approvalChains } = this.props;
    const { applicantOID, businessCode, formOID } = this.props.info
    if (approvalChains && approvalChains.length > 0) {
      this.setState({
        urgeLoading: true
      }, () => {
        const {approverOID, entityOID, entityType} = approvalChains[0];
        let params ={
          approverOID,
          entityOID,
          entityType,
          applicantOID,
          businessCode,
          formOID
        }
        adminApproveListService.postPressMessage(params)
          .then(res=>{
            if(res.data){
              message.info(messages('components.key746')/*已向审批人发出催办消息*/);
              setTimeout(() => {
                this.setState({ urgeLoading: false })
              }, 3000)
            }
          }).catch(e => {
          this.setState({ urgeLoading: false })
          message.error(`${e.response.data.message}`)
        });
      })
    }
  };

  render() {
    const { info, form, approvalChains, submitting } = this.props;
    const { deleting, withdrawing, printLoading, saving, urgeLoading } = this.state;
    let expenseReportStatus = getReportStatus(info);
    // 1002: 审批中,目前所有的单据都只在“审批中”才会展示催办按钮
    let showUrgeBtn = false // 单据是否需要展示催办按钮
      if (Number(info.status) === 1002) {
        // 报销单在处于“审批中”的状态时，有两种，一个是审批，一个是预审
        // 只在“审批中”--“审批”时展示催办按钮
        if (approvalChains && approvalChains.length > 0 && approvalChains[0].brmsRemark !== "财务预审") {
          showUrgeBtn = true
        }
      }
    return (
      <Affix offsetBottom={0} className="bottom-bar buttons-bar-bottom">
        <If value={submitting || deleting || withdrawing || printLoading || saving}>
          <div className="buttons-disabled-mask"/>
        </If>

        <If value={expenseReportStatus.operate === 'edit'}>
          <Button
            type="primary"
            className="back-btn"
            onClick={this.props.onSubmit}
            loading={submitting}
          >
            {messages('common.submit')/*提交*/}
          </Button>
        </If>

        <If value={expenseReportStatus.operate === 'edit'}>
          <Button
            className="back-btn delete-btn"
            loading={deleting}
            onClick={this.handleDelete}
          >
            {messages('common.delete')/*删除*/}
          </Button>
        </If>

        <If value={(
          info.withdrawEnable &&
          expenseReportStatus.operate === 'processing' &&
          approvalChains[0] && approvalChains[0].entityOID &&
          form.customFormPropertyMap && (
            Number(form.customFormPropertyMap['formWithdrawAuthority']) === 1 ||
            (Number(form.customFormPropertyMap['formWithdrawAuthority']) === 2 && info.withdrawFlag === 'Y')
          )
        )}>
          <Button
            className="back-btn"
            onClick={this.handleWithdraw}
            loading={withdrawing}
          >
            {messages('common.withdraw')/*撤回*/}
          </Button>
        </If>
        <If value={showUrgeBtn}>
          <Button
            className="back-btn"
            onClick={this.handelUrge}
            disabled={urgeLoading}
            type={'primary'}
          >
            催办
          </Button>
        </If>

        <If value={info.printView === 1 && false}>
          <Button
            type="primary"
            className="back-btn"
            onClick={this.handlePrint}
            loading={printLoading}
          >
            {messages('common.print')/*打印*/}
          </Button>
        </If>

        <If value={expenseReportStatus.operate === 'edit'}>
          <Button
            className="back-btn"
            onClick={this.handleSave}
            loading={saving}
          >
            {messages('common.save')/*保存*/}
          </Button>
        </If>

        <Button className="back-btn" onClick={this.goBack}>{messages("common.back")/*返回*/}</Button>
      </Affix>
    )
  }
}

ButtonsOnBottomBar.propTypes = {
  form: React.PropTypes.object,
  info: React.PropTypes.object,
  approvalChains: React.PropTypes.array,
  expenseReportInvoices: React.PropTypes.array,
  submitting: React.PropTypes.bool, //提交loading
  onSubmit: React.PropTypes.func,  //提交
};

ButtonsOnBottomBar.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
  }
}

export default connect(mapStateToProps)(ButtonsOnBottomBar)
